package com.example.chamberlainserver.config;

import com.volcengine.service.imagex.v2.ImagexService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Base64;

/**
 * 火山引擎 veImageX 配置类
 * 根据官方文档配置ImagexService实例
 */
@Configuration
public class VeImageXConfig {

    private static final Logger logger = LoggerFactory.getLogger(VeImageXConfig.class);

    @Value("${veimagex.access-key}")
    private String accessKey;

    @Value("${veimagex.secret-key}")
    private String secretKey;

    @Value("${veimagex.region}")
    private String region;

    @Value("${veimagex.service-id}")
    private String serviceId;

    /**
     * 创建ImagexService实例
     * 根据火山引擎官方文档初始化服务
     * @return ImagexService实例
     */
    @Bean
    public ImagexService imagexService() {
        try {
            logger.info("开始初始化ImagexService...");
            logger.info("配置信息 - Region: {}, ServiceId: {}", region, serviceId);
            logger.info("AccessKey: {}***{}", 
                accessKey != null && accessKey.length() > 8 ? accessKey.substring(0, 8) : "null",
                accessKey != null && accessKey.length() > 8 ? accessKey.substring(accessKey.length() - 4) : "");
            
            // 根据火山引擎官方文档，SecretKey应该直接使用原始值
            // 先尝试直接使用原始SecretKey，如果签名失败再考虑解码
            String actualSecretKey = secretKey;
            logger.info("SecretKey直接使用原始值（不进行Base64解码）");
            logger.info("原始SecretKey长度: {}", secretKey != null ? secretKey.length() : 0);
            logger.info("原始SecretKey: {}***{}", 
                secretKey != null && secretKey.length() > 8 ? secretKey.substring(0, 8) : "short",
                secretKey != null && secretKey.length() > 8 ? secretKey.substring(secretKey.length() - 4) : "");

            // 根据地域创建ImagexService实例
            ImagexService service;
            if ("ap-singapore-1".equals(region)) {
                logger.info("使用新加坡地域初始化ImagexService");
                service = ImagexService.getInstance("ap-singapore-1");
            } else {
                logger.info("使用默认地域（国内）初始化ImagexService");
                service = ImagexService.getInstance();
            }

            // 设置AK/SK到service实例
            service.setAccessKey(accessKey);
            service.setSecretKey(actualSecretKey);
            
            // 验证credentials设置
            logger.info("ImagexService credentials已设置完成");
            logger.info("最终使用的AccessKey: {}***{}", 
                accessKey != null && accessKey.length() > 8 ? accessKey.substring(0, 8) : "null",
                accessKey != null && accessKey.length() > 8 ? accessKey.substring(accessKey.length() - 4) : "");
            logger.info("最终使用的SecretKey长度: {}", actualSecretKey != null ? actualSecretKey.length() : 0);
            
            logger.info("ImagexService初始化成功");
            return service;
        } catch (Exception e) {
            logger.error("ImagexService初始化失败", e);
            throw new RuntimeException("Failed to initialize ImagexService: " + e.getMessage(), e);
        }
    }

    // Getter方法供其他组件使用
    public String getAccessKey() {
        return accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public String getRegion() {
        return region;
    }

    public String getServiceId() {
        return serviceId;
    }
}